const mysql = require('mysql')
    //连接数据库
const conn = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '135375',
    database: 'article',
    dateStrings: true, //转换时间类型数据 如果不设置时间数据将无法正常获取
});
conn.connect();
const db = {
    post(req, SuccessMessage, FailMessage, resp) {
        let data = [req.body.title, req.body.data],
            sql = `INSERT INTO listarticle (title,data) VALUES (?,?)`,
            callback = (err, res) => {
                if (!err) {
                    resp.send({
                        message: SuccessMessage,
                        Code: 200
                    })
                } else {
                    resp.send({
                        message: FailMessage
                    })
                }
            };
        conn.query(sql, data, callback)

    },
    delete(req, SuccessMessage, FailMessage, resp) {
        let sql = 'DELETE FROM listarticle WHERE id=?',
            data = [req.params.id],
            callback = (err, res) => {
                if (!err) {
                    resp.send({
                        message: SuccessMessage,
                        Code: 200
                    })
                } else {
                    resp.send({
                        message: FailMessage
                    })
                }

                resp.send()
            };
        conn.query(sql, data, callback)
    },
    put(id, SuccessMessage, FailMessage, req, resp) {
        let sql = 'UPDATE listarticle SET title=?,data=? WHERE id=?',
            data = [req.body.title, req.body.data, id],
            callback = (err, res) => {
                if (!err) {
                    resp.send({
                        body: res,
                        message: SuccessMessage,
                        Code: 200
                    })
                } else {
                    resp.send({
                        body: res.data,
                        message: FailMessage
                    })
                }
            };
        conn.query(sql, data, callback)
    },
    get(resp, SuccessMessage, FailMessage, sql, data) {
        let callback = (err, res) => {
            if (!err) {
                resp.send({
                    body: res,
                    message: SuccessMessage,
                    Code: 200
                })
            } else {
                resp.send({
                    body: res.data,
                    message: FailMessage
                })
            }
        };
        data = data;
        conn.query(sql, data, callback)
    }
}

module.exports = db;